<template>
    <!-- This section should be hidden by default and shown when there are todos -->
    <section class="main">
        <input id="toggle-all" class="toggle-all" type="checkbox" />
        <label for="toggle-all" @click="allChecked">Mark all as complete</label>
        <ul class="todo-list">
            <li :class="{ completed: item.status }" v-for="(item, index) in todoStore.todoList">
                <div class="view">
                    <input
                        class="toggle"
                        type="checkbox"
                        v-model="item.status"
                        @click="changeTodo(index)"
                    />
                    <label>{{ item.title }}</label>
                    <button class="destroy" @click="delTodoData(index)"></button>
                </div>
                <input class="edit" value="Create a TodoMVC template" />
            </li>
        </ul>
    </section>
</template>
<script lang="ts" setup>
import { onMounted } from 'vue';
import axios from 'axios';
import { todoRaw, useTodoStore } from '../store/todoStore'

//存储数据
const todoStore = useTodoStore();

//疯转
const TodoListShow = async () => {
    //发送请求
    var { data } = await axios.get('http://localhost:8000/todo')
    //    console.log(data);
    // todoList.data = data
    //把从服务器获取到的数据，直接存到容器中 pinia中
    //模板中可以直接获取到容器的额数据进行遍历循环
    //将从服务器获取到的数据传递给调用方法时addTodoStore方法
    todoStore.addTodoStore(data);
}
onMounted(TodoListShow)
//! 删除某一行
const delTodoData = async (index: any) => {
    //发送请求
    const serverBack = await axios.delete('http://localhost:8000/todo/' + todoStore.todoList[index].id)
    // console.log(serverBack);
    if (serverBack.status == 200) {
        //在pinia中书写删除页面中的该行
        todoStore.delTodoData(index)
    }
}
//修改
const changeTodo = async (index: any) => {
    todoStore.todoList[index].status = !todoStore.todoList[index].status;
    //发送请求
    const serverBack = await axios.put('http://localhost:8000/todo/' + todoStore.todoList[index].id, todoStore.todoList[index])
    console.log(serverBack);
}
//全选
// var off = true;
const allChecked = () => {

    // todoStore.todoList.forEach((item) => {
    //     if (off) {
    //         item.status = true
    //     } else {
    //         item.status = false
    //     }
    //     axios.put('http://localhost:8000/todo/' + item.id, item)
    // })
    // off = !off;
    // todoStore.todoList = todoStore.todoList.filter(async (item, index) => {
    //     if (item.status == false) {
    //         const todoDataType: todoRaw = {
    //             id: item.id,
    //             title: todoStore.todoList[index].title,
    //             status: true
    //         }
    //         axios.put('http://localhost:8000/todo/' + item.id, todoDataType)

    //     }

    //     return todoStore.todoList
    // })
    todoStore.allChecked()


}
</script>

<style>
</style>